package com.ho1ho.springboot.framework.core;

import javax.annotation.Resource;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.ho1ho.springboot.framework.core.auth.iters.UserDetail;
import com.ho1ho.springboot.framework.core.interceptors.ExecuteTimeInterceptor;
import com.ho1ho.springboot.framework.core.interceptors.GlobalEnvironmentInterceptor;
import com.ho1ho.springboot.framework.core.interceptors.MaintenanceInterceptor;

public abstract class BaseWebServerApplication implements WebMvcConfigurer, UserDetail {

	@Resource
	protected MaintenanceInterceptor maintenanceInterceptor;

	@Resource
	protected ExecuteTimeInterceptor executeTimeInterceptor;

	@Resource
	protected GlobalEnvironmentInterceptor globalEnvironmentInterceptor;

	// Add files folder to resource so that we can access upload files like this
	// below:
	// http://localhost:7070/files/image.jpg
	// http://stackoverflow.com/questions/36768656/spring-refering-the-resources-static-folder
	// http://www.webjars.org/documentation#springboot
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler(Const.UPLOAD_FILE_CONTEXT_PATH + "**")
				.addResourceLocations("file:" + Const.UPLOAD_FILE_FOLDER);

		// http://www.webjars.org/documentation#springboot

		// if (!registry.hasMappingForPattern("/webjars/**")) {
		// registry.addResourceHandler("/webjars/**")
		//// .addResourceLocations("/webjars/");
		// .addResourceLocations("classpath:/META-INF/resources/webjars/");
		// }
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		globalEnvironmentInterceptor.setUserDetail(this);
		
		registry.addInterceptor(executeTimeInterceptor);
		registry.addInterceptor(maintenanceInterceptor);
		registry.addInterceptor(globalEnvironmentInterceptor);

		// http://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter
		// registry.addInterceptor(new
		// TransactionInterceptor()).addPathPatterns("/person/save/*");
	}
}
